package com.yyk.yiliao.ui.activity.dingdan.fragment;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseFragment;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.ui.activity.detail.activity.PayPleaceOrder_Activity;
import com.yyk.yiliao.ui.activity.dingdan.activity.DingdanXiangqing4_Activity;
import com.yyk.yiliao.ui.activity.shopcart.ShopCart_Activity;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.DialogUtil;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.CartOrderdel_Info;
import com.yyk.yiliao.bean.CartOrderlist;
import com.yyk.yiliao.bean.CartStatuskey_Info;
import com.yyk.yiliao.bean.OderBuy_Info;
import com.yyk.yiliao.bean.OderOrderPay_Info;
import com.yyk.yiliao.bean.OrderOrderRestart_Info;
import com.yyk.yiliao.widget.diver.CustomDecoration;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 商品订单 全部
 */
public class Tab_One_Fragment extends BaseFragment {
    public static final String ARGS_PAGE = "Tab_One_Fragment";
    @BindView(R.id.nTab_rv)
    RecyclerView nTab_rv;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private BaseRecyclerAdapter<CartOrderlist.DataBean> adapter;
    private List<CartOrderlist.DataBean> data = new ArrayList<>();
    private int currentPage = 1;

    public static Tab_One_Fragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARGS_PAGE, page);
        Tab_One_Fragment fragment = new Tab_One_Fragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getLayoutId() {
        return R.layout.fragment_tab1;
    }

    /**
     * 这里控制可见的时候加载数据
     *
     * @param isVisible true  不可见 -> 可见
     */
    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        super.onFragmentVisibleChange(isVisible);
        if (isVisible) {
            currentPage = 1;
            setOne(currentPage, true);
        } else {

        }
    }

    @Override
    public void initView() {
        initRefreshLoadMore();
    }

    @Override
    public void initData() {
        initAdapter();
        setOne(currentPage, true);
    }

    private void initAdapter() {
        adapter = new BaseRecyclerAdapter<CartOrderlist.DataBean>(getActivity(), data, R.layout.adapter_item_c_tab_one) {
            @Override
            public void convert(BaseRecyclerHolder holder, CartOrderlist.DataBean info, final int position, boolean isScrolling) {
                LinearLayout ll_zk = holder.getView(R.id.ll_zk); //总布局
                TextView tv_confirm = holder.getView(R.id.tv_confirm);//再次购买
                TextView tv_confirm2 = holder.getView(R.id.tv_confirm2);//确认收收获
                TextView tv_pay = holder.getView(R.id.tv_pay);//支付
                TextView tv_delete = holder.getView(R.id.tv_delete);//删除订单
                TextView tv_delete2 = holder.getView(R.id.tv_delete2); //取消订单
                TextView tv_pinglun = holder.getView(R.id.tv_pinglun);//评论
                int status = info.getStatus();
                if (status == 1) {
                    holder.setText(R.id.tv_status, "待付款");
                    tv_delete2.setVisibility(View.VISIBLE);
                    tv_pay.setVisibility(View.VISIBLE);
                    tv_delete.setVisibility(View.GONE);
                    tv_confirm.setVisibility(View.GONE);
                    tv_confirm2.setVisibility(View.GONE);
                } else if (status == 2) {
                    holder.setText(R.id.tv_status, "已付款");
                    ll_zk.setVisibility(View.GONE);

                } else if (status == 3) {
                    holder.setText(R.id.tv_status, "等待商家发货");
                    ll_zk.setVisibility(View.GONE);
                } else if (status == 4) {
                    holder.setText(R.id.tv_status, "已发货");
                    tv_confirm2.setVisibility(View.VISIBLE);
                    tv_delete2.setVisibility(View.GONE);
                    tv_pay.setVisibility(View.GONE);
                    tv_delete.setVisibility(View.GONE);
                    tv_confirm.setVisibility(View.GONE);
                } else if (status == 5) {
                    holder.setText(R.id.tv_status, "已完成");
                    tv_delete.setVisibility(View.VISIBLE);
                    tv_pinglun.setVisibility(View.VISIBLE);
                    tv_confirm.setVisibility(View.VISIBLE);

                    tv_delete2.setVisibility(View.GONE);
                    tv_confirm2.setVisibility(View.GONE);
                } else if (status == 6) {
                    holder.setText(R.id.tv_status, "已取消");
                    tv_delete.setVisibility(View.VISIBLE);
                    tv_confirm.setVisibility(View.VISIBLE);

                    tv_delete2.setVisibility(View.GONE);
                    tv_confirm2.setVisibility(View.GONE);
                    tv_pay.setVisibility(View.GONE);

                }
                holder.setText(R.id.tv_stname, info.getStname());
                holder.setText(R.id.tv_total_num, "共" + info.getAllnum() + "件商品 已付款：");
                holder.setText(R.id.tv_total_money, "¥" + info.getAllmoney());
                final String number = info.getNumber();
                RecyclerView rv = holder.getView(R.id.rv);
                //删除订单
                tv_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog builder = DialogUtil.getIntanse().simpleDialog(getContext(), null, "确定删除该订单吗？", "确定", "取消", new DialogUtil.AlertDialogListenter() {
                            @Override
                            public void queding() {
                                initDeleteDingdan(number, position);
                            }

                            @Override
                            public void quxiao() {
//                                ToastUtil.showShort(getContext(), "取消");

                            }
                        });

                        builder.show();
                    }
                });
                //取消订单
                tv_delete2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog builder = DialogUtil.getIntanse().simpleDialog(getContext(), null, "确定取消该订单吗？", "确定", "取消", new DialogUtil.AlertDialogListenter() {
                            @Override
                            public void queding() {
                                initQuxiaoDingdan(number, 6, position);
                            }

                            @Override
                            public void quxiao() {

                            }
                        });

                        builder.show();
                    }
                });
                //再次购买
                tv_confirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initGoumaiDingdan(number);

                    }
                });
                //确认收货
                tv_confirm2.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        AlertDialog builder = DialogUtil.getIntanse().simpleDialog(getContext(), null, "确定已收到货品？", "确定收货", "取消", new DialogUtil.AlertDialogListenter() {
                            @Override
                            public void queding() {
                                initQuerenDingdan(number, 5, position);
                            }

                            @Override
                            public void quxiao() {

                            }
                        });

                        builder.show();
                    }
                });
                //去支付
                tv_pay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        initPay(number);

                    }
                });
                rv.setLayoutManager(new LinearLayoutManager(getActivity()));
                rv.addItemDecoration(new CustomDecoration(getActivity(), CustomDecoration.VERTICAL_LIST, R.drawable.divider_f8_shopdingdan, 0));

                BaseRecyclerAdapter<CartOrderlist.DataBean.ListBean> baseRecyclerAdapter = new BaseRecyclerAdapter<CartOrderlist.DataBean.ListBean>(getContext(), info.getList(), R.layout.adapter_item_c_tab_one_one) {
                    @Override
                    public void convert(BaseRecyclerHolder holder, CartOrderlist.DataBean.ListBean item, int position, boolean isScrolling) {
                        holder.setText(R.id.tv_sname, item.getSname());
                        holder.setText(R.id.tv_money, "¥" + item.getMoney());
                        holder.setText(R.id.tv_num, "X" + item.getNum());
                        holder.setImageByUrl(R.id.iv_img, ApiService.BASE_URL + item.getImg());
                    }
                };
                rv.setAdapter(baseRecyclerAdapter);
                baseRecyclerAdapter.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(RecyclerView parent, View view, int pp) {
                        initDingDanXiangqing(data.get(position).getNumber(), position, data.get(position).getStatus());
                    }
                });


            }


        };
        nTab_rv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        nTab_rv.addItemDecoration(new CustomDecoration(getActivity(), CustomDecoration.VERTICAL_LIST, R.drawable.divider_f8_10, 0));
        nTab_rv.setAdapter(adapter);

    }

    private void initRefreshLoadMore() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                currentPage++;
                setOne(currentPage, false);
                refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                setOne(currentPage, true);
                refreshLayout.finishRefresh();
            }
        });
    }
    /**
     *
     * 全部
     * @param currentPage
     * @param flag
     */
    private void setOne(int currentPage, final boolean flag) {
        Map<String, String> map = new TreeMap<>();
        map.put("uid", String.valueOf(Hawk.get("uid", 0)));
        map.put("status", "");
        map.put("page", String.valueOf(currentPage));
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartOrderlist(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartOrderlist>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        Logger.e("商品订单全部"+e.getMessage());
                    }

                    @Override
                    public void onNext(CartOrderlist info) {
                        Logger.e("商品订单"+info.toString());
                        if (info.getCode() == 1) {
                            if (flag) {
                                data.clear();
                            }
                            if (null != info.getData() && info.getData().size() > 0) {
                                data.addAll(info.getData());
                            } else {
                                ToastUtil.showShort(getActivity(), "已经没有数据了");
                            }
                            adapter.notifyDataSetChanged();
                            adapter.onAttachedToRecyclerView(nTab_rv);
                        }
                    }
                });
    }


    /**
     * 订单详情  待收货
     *
     * @param id
     * @param postion
     */
    private void initDingDanXiangqing(String id, final int postion, final int status) {
        Map<String, String> map = new TreeMap<>();
        map.put("type", "2");
        map.put("order_code", id + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postOrderOrderRestart(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<OrderOrderRestart_Info>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(OrderOrderRestart_Info info) {
                        if (info.getCode() == 1) {
                            info.setPostion(postion);
                            info.setZkstatus(status);
                            Intent intent = new Intent(getActivity(), DingdanXiangqing4_Activity.class);
                            EventBus.getDefault().postSticky(info);
                            startActivity(intent);

                        } else {

                        }
                    }
                });
    }

    /**
     * 去支付
     */
    public void initPay(String number) {
        Map<String, String> map = new TreeMap<>();
        map.put("number", number);
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postOderOrderPay(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<OderOrderPay_Info>() {


                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(OderOrderPay_Info info) {
                        if (info.getCode() == 1) {
//                            Intent intent = new Intent(getContext(), PayPleaceOrder_Activity.class);
////                            EventBus.getDefault().postSticky(info);
//                            EventBus.getDefault().postSticky(new PayMessage(2, info.getAddtime(), info.getOrder_code(), info.getTotal(), info.getPay_type()));
//                            startActivity(intent);
//                            getActivity().finish();

                            Bundle bundle = new Bundle();
                            //1. 购物车结算呢
                            bundle.putString("endtype", "1");
                            bundle.putString("out_trade_no", info.getOrder_code() + "");
                            bundle.putString("total", info.getTotal() + "");
                            bundle.putString("addtime", info.getAddtime() + "");
                            startAct(PayPleaceOrder_Activity.class, bundle);
                        }
                    }
                });
    }

    /**
     * 确认收货
     *
     * @param id
     * @param status
     * @param postion
     */
    public void initQuerenDingdan(String id, int status, final int postion) {
        Map<String, String> map = new TreeMap<>();
        map.put("id", id + "");
        map.put("status", status + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartStatuskey(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartStatuskey_Info>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(CartStatuskey_Info info) {
                        if (info.getCode() == 1) {
                            ToastUtil.showShort(getActivity(), info.getMsg());
                            adapter.delete(postion);
//                            setThree();
                        }
                    }
                });
    }

    /**
     * 再次购买
     *
     * @param id
     */
    public void initGoumaiDingdan(String id) {
        Map<String, String> map = new TreeMap<>();
        map.put("number", id + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postOderBuy(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<OderBuy_Info>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(OderBuy_Info info) {
                        if (info.getCode() == 1) {
                            Intent intent = new Intent(getActivity(), ShopCart_Activity.class);
                            startActivity(intent);
//                            getActivity().finish();
                        } else {
                            ToastUtil.showShort(getActivity(), "商品已失效");
                        }
                    }
                });
    }

    /**
     * 删除订单
     *
     * @param number
     */
    public void initDeleteDingdan(String number, final int postion) {
        Map<String, String> map = new TreeMap<>();
        map.put("number", number);
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartOrderdel(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartOrderdel_Info>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(CartOrderdel_Info info) {
                        if (info.getCode() == 1) {
                            ToastUtil.showShort(getActivity(), info.getMsg());
                            adapter.delete(postion);
                        } else {
                            ToastUtil.showShort(getActivity(), info.getMsg());
                        }
                    }
                });
    }

    /**
     * 取消订单
     *
     * @param number
     * @param status
     */
    public void initQuxiaoDingdan(String number, int status, final int postion) {
        Map<String, String> map = new TreeMap<>();
        map.put("number", number + "");
        map.put("status", status + "");
map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartStatuskey(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartStatuskey_Info>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(CartStatuskey_Info info) {
                        if (info.getCode() == 1) {
                            ToastUtil.showShort(getActivity(), info.getMsg());
                            adapter.delete(postion);
                        }
                    }
                });
    }


}
